package com.cheng.example.excel.easyexcel.util.util;

import com.alibaba.excel.EasyExcel;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EasyExcelUtil {




    /**
	 * 解析Excel成json
	 * @param inputStream
	 * @return
	 * @throws Exception
	 */
    public static String readExcel(InputStream inputStream, String[] title) throws Exception {
        // 这里也可以不指定class，返回一个list，然后读取第一个sheet 同步读取会自动finish
        List<Map<Integer, String>> listMap = EasyExcel.read(inputStream).sheet().headRowNumber(1).doReadSync();
		int endRow=listMap.size();

		Map<Integer, String> titleMap = listMap.get(0);
		int columns = listMap.get(0).size();
		List<Map<Object, Object>> content = new ArrayList<Map<Object, Object>>();

		for(int i=1; i<endRow; i++){
			Map<Object, Object> rowContent = new HashMap<Object, Object>();
			for ( String code : title ){
			    rowContent.put(code, "");
			}
			for ( int j=0; j<columns; j++ ){
				rowContent.put(titleMap.get(j), listMap.get(i).get(j));
			}
			content.add(rowContent);
		}

		String jsonStr = JsonUtil.writeValue(content);

		return jsonStr;
	}
}
